#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion

using System;
using UnityEngine;

namespace Neatly.UI
{
    public class NScaleListener : NUIBehaviour
    {

        private Vector2 LastPos1, LastPos2;

        private Action<float> m_ScaleAction;

        private void Start()
        {
            NImage image = null;
            //NeatlyTimer.AddFrame(gameObject, OnUpdate);
        }
        
        private void LateUpdate()
        {
            #if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.LeftAlt))
            {
                LastPos1 = Input.mousePosition;
            }
            if (Input.GetMouseButtonDown(0))
            {
                LastPos2 = Input.mousePosition;
            }
            if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0))
            {
                var pos1 = LastPos1;
                var pos2 = Input.mousePosition;

                var lastDistance = Vector2.Distance(LastPos1, LastPos2);
                var newDistance = Vector2.Distance(pos1, pos2);
                var offset = newDistance - lastDistance;
                var scaleFactor = offset / 100 * transform.lossyScale.x;
                m_ScaleAction?.Invoke(scaleFactor);
                LastPos1 = pos1;
                LastPos2 = pos2;
            }
            #else
            if (Input.touchCount == 2)
            {
                var pos1 = Input.GetTouch(0).position;
                var pos2 = Input.GetTouch(1).position;

                for (var i = 0; i < Input.touchCount; i++)
                {
                    var phase = Input.GetTouch(i).phase;
                    if (phase == TouchPhase.Began || phase == TouchPhase.Canceled || phase == TouchPhase.Ended)
                    {
                        LastPos1 = pos1;
                        LastPos2 = pos2;
                        return;
                    }
                }

                var lastDistance = Vector2.Distance(LastPos1, LastPos2);
                var newDistance = Vector2.Distance(pos1, pos2);
                var offset = newDistance - lastDistance;
                var scaleFactor = offset / 100;
                m_ScaleAction?.Invoke(scaleFactor);

                LastPos1 = pos1;
                LastPos2 = pos2;
            }
            #endif
        }

        public void AddScaleAction(Action<float> action)
        {
            m_ScaleAction = action;
        }
    }
}